package com.ukao.pad.dialog;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ukao.pad.R;
import com.ukao.pad.base.BaseDialogFragment;
import com.ukao.pad.bean.ProductBatchInBean;
import com.ukao.pad.bean.StringBean;
import com.ukao.pad.consts.Constant;
import com.ukao.pad.consts.SaveParamets;
import com.ukao.pad.eventbus.MembershipCardEvent;
import com.ukao.pad.retrofit.ApiCallback;
import com.ukao.pad.usbrfidreader.UsbrfidReaderHelper;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.widget.ClearEditText;
import com.ukao.pad.widget.StateButton;
import com.ukao.pad.widget.StateImageView;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Observable;

/**
 * Created by ukaodev on 2017/7/29.
 */

public class StartCountDialogFragment extends BaseDialogFragment {


    @BindView(R.id.close_btn)
    RelativeLayout closeBtn;
    @BindView(R.id.finish_btn)
    StateButton finishBtn;
    @BindView(R.id.search_edit_text)
    ClearEditText searchEditText;
    @BindView(R.id.search_button)
    StateImageView searchButton;
    @BindView(R.id.count_state)
    ImageView countState;
    @BindView(R.id.factory_count_txt)
    TextView factoryCountTxt;
    @BindView(R.id.count_layout)
    LinearLayout countLayout;
    @BindView(R.id.rfid_btn)
    StateImageView rfidBtn;


    private List<ProductBatchInBean> mFactoryBatchInBean;

    private OnCounntSucceedListener monCounntSucceed;

    boolean isLeaveFactoryEnter;
    private Unbinder unbinder;
 boolean  isCheckSucceed=false;  //是否核对

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFactoryBatchInBean = getArguments().getParcelableArrayList(ARG_PARAM1);
        isLeaveFactoryEnter = getArguments().getBoolean(ARG_PARAM2);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.popwin_count, container, false);
        unbinder = ButterKnife.bind(this, view);
        initListener();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        UsbrfidReaderHelper.getInstance().readCardNum();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        UsbrfidReaderHelper.getInstance().cancelReadCardNum();
        if (mOnConfirmClickListener!=null){
            mOnConfirmClickListener.onChildItemClick(isCheckSucceed ? Constant.START_COUNT_DESTROY : Constant.ON_DESTORY, "");
        }
        if (monCounntSucceed!=null){monCounntSucceed=null;}
        unbinder.unbind();
    }






    @Override
    protected void initListener() {
        super.initListener();
        closeBtn.setOnClickListener(mOnClickListener);
        finishBtn.setOnClickListener(mOnClickListener);
        searchButton.setOnClickListener(mOnClickListener);
        rfidBtn.setOnClickListener(mOnClickListener);
        searchEditText.setOnEditorActionListener(mOnEditorAction);
    }

    TextView.OnEditorActionListener mOnEditorAction = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) {

                searchedBatchIn();

            }
            return false;
        }
    };

    public interface OnCounntSucceedListener {
        void onCounntSucceed(int  pos);

    }


    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(MembershipCardEvent event) {

        switch (event.getMessage()) {
            case cardNum:/*成功*/

                String rfidSecretCard = (String) event.getData();
                searchEditText.setText(rfidSecretCard);
                searchedBatchIn();
                break;


        }
    }


    public void setOnCounntSucceedListener(OnCounntSucceedListener monCounntSucceed) {
        this.monCounntSucceed = monCounntSucceed;
    }

    View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.rfid_btn:
                    UsbrfidReaderHelper.getInstance().readCardNum();
                    break;
                case R.id.finish_btn:
                    dismiss();
                    break;
                case R.id.close_btn:
                    dismiss();
                    break;
                case R.id.search_button:

                    searchedBatchIn();
                    hideKeyboard();


                    break;

            }

        }
    };

    private void searchedBatchIn() {
        String stredittext = searchEditText.getText().toString().trim();
        if (!stredittext.isEmpty()) {
            for (int i = 0; i < mFactoryBatchInBean.size(); i++) {
                ProductBatchInBean mBatchInBean = mFactoryBatchInBean.get(i);
                if (stredittext.equals(mBatchInBean.getScanCode())) {
                    confirmFactory(mBatchInBean,i);
                }else  if (stredittext.equals(mBatchInBean.getBindCode()) ){
                    confirmFactory(mBatchInBean,i);
                }
            }


        }
    }



    public void confirmFactory(final ProductBatchInBean mBatchInsBean,final  int  pos  ) {


        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("id", mBatchInsBean.getId());//批次关联衣物  id,outId,orderProId
        if (isLeaveFactoryEnter) {
            mHashMap.put("outId", mBatchInsBean.getOutId());
            mHashMap.put("orderProId", mBatchInsBean.getOrderProId());//衣物

        } else {
            if ( mBatchInsBean.isOrder()){
                mHashMap.put("id", mBatchInsBean.getId()); /*订单衣物*/

            }else{
                mHashMap.put("inId", mBatchInsBean.getInId());
                mHashMap.put("orderProId", mBatchInsBean.getOrderProId());//衣物

            }


        }
        mHashMap.put("accessToken", SaveParamets.getToken(getContext()));
        Observable mObservable = null;
        if (isLeaveFactoryEnter) {
            mObservable = apiStores().leaveCount(Constant.createParameter(mHashMap));
        } else {
            if (mBatchInsBean.isOrder()){
                mObservable = apiStores().clothingInConfirm(Constant.createParameter(mHashMap));
            }else{
                mObservable = apiStores().confirmFactory(Constant.createParameter(mHashMap));
            }

        }
        cleanCode();
        addSubscription(mObservable,
                new ApiCallback<StringBean>() {
                    @Override
                    public void onSuccess(StringBean model) {

                        switch (model.getHttpCode()) {
                            case 200:
                                isCheckSucceed=true;
                                if (monCounntSucceed != null) {
                                    monCounntSucceed.onCounntSucceed( pos);
                                    factoryCountTxt.setText(mBatchInsBean.getProductName() + "\n" + mBatchInsBean.getScanCode());
                                    countState.setImageResource(R.drawable.factory_count_succeed);
                                    factoryCountTxt.setTextColor(getContext().getResources().getColor(R.color.white));
                                }
                                break;
                            default:
                                countState.setImageResource(R.drawable.factory_count_fail);
                                factoryCountTxt.setText(model.getMsg());
                                factoryCountTxt.setTextColor(getContext().getResources().getColor(R.color.normal_red));
                                break;
                        }
                        if (countLayout.getVisibility() == View.GONE)
                            countLayout.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onNoNewWork() {

                    }


                    @Override
                    public void onFinish() {

                    }
                });
    }

    private void cleanCode() {

        searchEditText.setText("");
        searchEditText.requestFocus();


    }

}
